package com.scalar.chiptrack.finance.creditNote.actionCommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.finance.creditNote.dao.CreditNoteDAO;
import com.scalar.chiptrack.finance.creditNote.forms.CreditNoteForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * User: Sujan
 * Date: Apr 13, 2007
 * Time: 2:46:50 PM
 */
public class CreditNoteSearchCommand extends ActionCommand
{

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        HttpSession session  = request.getSession();
        User user            = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        CreditNoteForm creditNoteForm = (CreditNoteForm) form;
        HashMap errors = (HashMap)request.getAttribute( SessionKeys.ERROR_MESSAGES );
        HashMap info = (HashMap)request.getAttribute( SessionKeys.INFO_MESSAGES );

        request.setAttribute ( "customers", CustomerDAO.getAllCustomerNamesByUserType ( null, user ) );
        String isSearchSubmit = request.getParameter( "isSearchSubmit" );
        if ( isSearchSubmit != null && "true".equalsIgnoreCase( isSearchSubmit ) )
        {
            ArrayList creditNotesList = CreditNoteDAO.loadCreditNotesList( null, creditNoteForm.getCustomerId(), creditNoteForm.getSalesOrderNo(), creditNoteForm.getCreditNoteNumber(), creditNoteForm.getNoteType(), creditNoteForm.getStatus(), creditNoteForm.getFromDate(), creditNoteForm.getToDate());
            if ( creditNotesList == null || creditNotesList.isEmpty() )
            {
                errors.put( "No Credit/Debit Note(s) available for the given search criteria", null );
            }
            else
            {
                request.setAttribute ( "creditNotesList", creditNotesList );
            }
        }
        return mapping.findForward( "search" );
    }
}
